package metier;
import java.util.List;


import modele.Client;

import org.hibernate.Session;
import org.hibernate.Transaction;
import dao.ArticleDAO;
import dao.ClientDAO;
import dao.TaxeDAO;
import persistence.BaseDAO;
import utils.Util;


public class ClientManager {
	
	public static List getAllClients()	throws Exception {
		Session session = BaseDAO.getInstance().openSession();
		try {
			List list  = ClientDAO.getListClients("from Client",session);
			session.close();
			return list;
		} catch (Exception e) {
			e.printStackTrace();			
			throw new Exception(e.getMessage());
		}
	}

	public static List getClients(int start, int limit) throws Exception {
		Session session = BaseDAO.getInstance().openSession();
		try {
			List list  = ClientDAO.getListClients("from Client",session,start,limit);
			session.close();
			return list;
		} catch (Exception e) {
			e.printStackTrace();			
			throw new Exception(e.getMessage());
		}
	}

	public static List ajouterClients(Object data) throws Exception {
		Session session = BaseDAO.getInstance().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			List<Client> lToAdd =Util.getClientFromRequest(data);
			for (Client client : lToAdd) {
				ClientDAO.ajouterClient(client, session);
			}
			tx.commit();
			session.close();
			return lToAdd;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();			
			throw new Exception(e.getMessage());
		}
	}

	public static List modfierClients(Object data)throws Exception {
		Session session = BaseDAO.getInstance().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			List<Client> lToUpdate =Util.getClientFromRequest(data);
			for (Client client : lToUpdate) {
				ClientDAO.modifierClient(client, session);
			}
			tx.commit();
			session.close();
			return lToUpdate;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();			
			throw new Exception(e.getMessage());
		}
	}

	public static boolean supprimerClients(Object data) throws Exception {
		Session session = BaseDAO.getInstance().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			//it is an array - have to cast to array object
			if (data.toString().indexOf('[') > -1){
				List<Integer> deleteClients = Util.getListIdFromJSON(data);
				for (Integer id : deleteClients){
					ClientDAO.SupprimerClient(ClientDAO.getClient(id, session), session);
				}
			} else { //it is only one object - cast to object/bean
				Integer id = Integer.parseInt(data.toString());
				ClientDAO.SupprimerClient(ClientDAO.getClient(id, session), session);
			}
			tx.commit();
			session.close();
			return true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();			
			throw new Exception(e.getMessage());
		}
	}
}
